package com.xiaoma.thread.wait.connectionpool;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * @author xiaomacdut
 * @date 2020年3月7日 下午12:06:23
 */
public class Test{
    
    public static void main(String [] args){
        int allNum = 100;
        AtomicInteger successNum = new AtomicInteger(0);
        ConnectionPoolOfWaitNotify connectionPoolOfWaitNotify = new ConnectionPoolOfWaitNotify();
        
        IntStream.rangeClosed(1, allNum).parallel().forEach(i-> {
            Connection connection = null;
            try{
                connection = connectionPoolOfWaitNotify.getConnectioin(100);
                if(null != connection){
                    successNum.addAndGet(1);
                    System.out.println("线程" + i + "拿到连接" + connection.getConnectionName());
                    Thread.sleep(200);
                }else{
                    System.out.println("线程" + i + "没有拿到连接");
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                if(null != connection){
                    connectionPoolOfWaitNotify.revertConnection(connection);
                }
            }
        });
        
        System.out.println("总共拿连接次数：" + allNum + "，拿到连接次数：" + successNum.get());
    }
}
